#!/usr/bin/env python3
# -*- coding: utf-8 -*-
"""
script name: youdao
Created on 2020/2/8 18:22 by PyCharm
@author: fujianjian
"""
import logging

import pymysql
import requests
from bs4 import BeautifulSoup


class YouDao(object):
    search_url = 'http://dict.youdao.com/w/%s/#keyfrom=dict2.top'
    data_host = 'localhost'
    data_port = 33006
    data_username = 'root'
    data_password = 'root'
    data_test_sql = 'select version();'

    def __init__(self) -> None:
        super().__init__()
        logging.basicConfig(level=logging.INFO,
                            # format='%(asctime)s ::%(module)s :: %(process)s-%(processName)s :: %(thread)s-%(threadName)s :: %(pathname)s :: %(filename)s :: %(levelname)s :: %(lineno)s :: %(funcName)s :: %(message)s')
                            format='%(asctime)s ::%(module)s :: %(process)s-%(processName)s :: %(thread)s-%(threadName)s :: %(pathname)s :: %(levelname)s :: %(lineno)s :: %(funcName)s :: %(message)s'
                            )

        try:
            # 打开数据库链接 pymysql.connect(host, username, password, database)
            self.db = pymysql.connect(host=self.data_host,
                                      port=self.data_port,
                                      user=self.data_username,
                                      password=self.data_password,
                                      database='mansite',
                                      charset='utf8')
            cursor = self.db.cursor()
            cursor.execute(self.data_test_sql)
            ret = cursor.fetchone()
            logging.info('connected mysql and test result: %s' % ret)
            cursor.execute('show tables')
            tables = cursor.fetchall()
            table_name = [name for table in tables for name in table]
            logging.info('connected mysql and table list: %s' % table_name)

            if 'trans_word' not in table_name:
                self.__init_table()
                logging.info('connected mysql and init tables')

            logging.info('connect mysql success')
        except EOFError as eof:
            self.log.info('connect database error', eof)

    def search_word(self, word, trans_type='中英') -> str:
        """
        查询单词
        :param word:
        :param trans_type:
        :return:
        """
        logging.error('search word function， the word: %s' % word)
        ret = self.__search_local_word(word, trans_type)
        if ret:
            logging.info('search word result: %s' % ret[0][2])
        else:
            packstr, net_str = self.__search_word_net(word, trans_type)
            if net_str:
                self.__save_keyword(word, net_str, trans_type)

            logging.info('search word with net: %s' % packstr)

        pass

    def __search_word_net(self, word, trans_type='中英') -> str:
        """
        通过网络查询单词
        :param word:
        :param trans_type:
        :return:
        """
        logging.info('start search word from net, word: %s', word)

        try:
            res = requests.get(url=self.search_url % word)
            soup = BeautifulSoup(res.text, 'lxml')
            s = soup.find(class_='trans-container')('ul')[0]('li')
            net_str = ''
            string = '本地词库尚未收录或拼写不全, 查看有道在线直接查询匹配结果:'
            for item in s:
                if item.text:
                    net_str += str(item.text)

        except Exception as e:
            logging.error('search word from net error %s' % e)
            string = '请检查网络连接或者词条拼写是否正确'
            net_str = ''
        finally:
            logging.info('completed search word from net, word: %s' % word)
            return string + net_str, net_str

        pass

    def __save_keyword(self, *word_info):

        save_sql = 'insert into trans_word (keyword, trans_text, trans_type) values (%s, %s, %s)'
        try:
            cursor = self.db.cursor()
            cursor.execute(save_sql, word_info)
            self.db.commit()
        except Exception as e:
            logging.error('save word info error %s' % e)
            # 插入失败回滚插入操作
            self.db.rollback()
        finally:
            cursor.close()

        pass

    def __search_local_word(self, word, trans_type):

        search_sql = "select * from trans_word where keyword = %s and trans_type = %s"
        try:
            cursor = self.db.cursor()
            cursor.execute(search_sql, (word, trans_type))
            ret = cursor.fetchall()
            logging.info('search local ret: %s' % ret)
            return ret

        except Exception as e:
            logging.error('search local word error %s' % e)

        finally:
            cursor.close()

    def __init_table(self):

        init_sql = """
create table if not exists trans_word(
  id integer primary key auto_increment comment '主键',
  keyword varchar(127) not null comment '关键字',
  trans_text varchar(256) comment '译文',
  trans_type varchar(32) not null comment '翻译类别',
  created_time timestamp default current_timestamp comment '创建时间',
  updated_time timestamp default current_timestamp comment '更新时间'
) engine=InnoDB default charset=utf8 comment '翻译词汇表';
        """
        self.db.cursor().execute(init_sql)
        self.db.commit()

        pass

    def __reduce__(self) -> tuple:
        self.db.close()
        return super().__reduce__()


if __name__ == '__main__':
    youdao = YouDao()
    youdao.search_word('hello world')
    # while True:
    while False:
        keyword = input('input keyword: ')
        if keyword:
            if keyword == 'exit':
                break
            else:
                trans_ret = youdao.search_word(keyword)
                logging.info('trans ret: %s' % trans_ret)
        pass

    exit(0)
